package com.jinlejia.erp.ui.new_house.house;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.ui.new_house.adapter.PictureViewPager;
import com.jinlejia.erp.utils.StringUtil;
import com.jinlejia.erp.widget.HackyViewPager;
import com.weight.CustomToast;

import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;


/**
 * 户型图
 */

public class HouseTypeActivity extends AppCompatActivity {

    private ImageView back;
    private TextView save, tvHousetype, tvjunPrice;
    private HackyViewPager viewPager;
    private JSONObject jsonObject;
    private PictureViewPager adapter;
    private int currentPosition;
    private RelativeLayout toplayout;
    private RelativeLayout bottomlayout;
    private TextView count;
    private TextView prices;
    private TextView area;
    private TextView house_type;
    private boolean isShow = true;
    private AlphaAnimation mShowAnim;
    private AlphaAnimation hiddenAmin;
    private List<String> list;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_house_type);
        EventBus.getDefault().registerSticky(this);
        initView();
        getData();
    }

    /**
     * 初始化视图
     * fadsxjvxcovdamflsdjflkdfdlscmdkljfkdlsjfenfdcjdlcdjslfjdsklfjdaslcmxc
     */
    private void initView() {
        if (getIntent().hasExtra("position")) {
            currentPosition = getIntent().getIntExtra("position", 0);
        }
        viewPager = (HackyViewPager) findViewById(R.id.id_picture_album);
        back = (ImageView) findViewById(R.id.id_back);
        save = (TextView) findViewById(R.id.save_picture);
        toplayout = (RelativeLayout) findViewById(R.id.id_action_layout);
        bottomlayout = (RelativeLayout) findViewById(R.id.id_bottom_layout);
        count = (TextView) findViewById(R.id.count);
        prices = (TextView) findViewById(R.id.price);
        area = (TextView) findViewById(R.id.area);
        house_type = (TextView) findViewById(R.id.house_type);
        tvHousetype = findViewById(R.id.tvHousetype);
        tvjunPrice = findViewById(R.id.tvjunPrice);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new getImageCacheAsyncTask(HouseTypeActivity.this)
                        .execute(ApiConfig.MAGEHEADER_URL().concat(list.get(currentPosition).toString()));
            }
        });

       /* viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentPosition = position;
                count.setText(position+ 1 + "/" + list.size());
                title.setText(StringUtil.valueOf(dataList.get(position).get("picName")));
                if (!TextUtils.isEmpty(StringUtil.valueOf(dataList.get(position).get("price")))){
                    prices.setText(StringUtil.valueOf(dataList.get(position).get("price")).concat("万"));
                }
                if (!TextUtils.isEmpty(StringUtil.valueOf(dataList.get(position).get("acreage")))){
                    area.setText(StringUtil.valueOf(dataList.get(position).get("acreage")).concat("㎡"));
                }
                if (!TextUtils.isEmpty(StringUtil.valueOf(dataList.get(position).get("houseType")))){
                    house_type.setText(StringUtil.valueOf(dataList.get(position).get("houseType")));
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });*/

        //控件显示的动画
        mShowAnim = new AlphaAnimation(0.0f, 1.0f);
        mShowAnim.setDuration(300);

        //控件隐藏的动画
        hiddenAmin = new AlphaAnimation(1.0f, 0.0f);
        hiddenAmin.setDuration(300);

    }

    private void getData() {
        try {
            JSONObject housePicInfo=new JSONObject(String.valueOf(getIntent().getStringExtra("json")));
            String picUrl = String.valueOf(housePicInfo.get("picUrl"));
            list= new ArrayList<>();
            list.add(picUrl);
            adapter = new PictureViewPager(HouseTypeActivity.this, (ArrayList<String>) list);
            viewPager.setAdapter(adapter);
            viewPager.setCurrentItem(currentPosition);

            if (TextUtils.isEmpty(StringUtil.valueOf(housePicInfo.get("price")))||String.valueOf(housePicInfo.get("price")).equals("0.0")||String.valueOf(housePicInfo.get("price")).equals("0")){
                prices.setText("价格待定");
            }else{
                prices.setText(StringUtil.valueOf(housePicInfo.get("price")).concat("万"));
            }
            if (!TextUtils.isEmpty(StringUtil.valueOf(housePicInfo.get("acreage")))){
                area.setText(StringUtil.valueOf(housePicInfo.get("acreage")).concat("㎡"));
            }
            if (!TextUtils.isEmpty(StringUtil.valueOf(housePicInfo.get("houseType")))){
                house_type.setText(StringUtil.valueOf(housePicInfo.get("houseType")));
            }
            if (!TextUtils.isEmpty(StringUtil.valueOf(housePicInfo.get("property")))){
                tvHousetype.setText(StringUtil.valueOf(housePicInfo.get("property")));
            }

            if (Integer.parseInt(String.valueOf(housePicInfo.get("saleState"))) == 1){
                tvjunPrice.setText("价格待定");
            }else{
                if (!TextUtils.isEmpty(StringUtil.valueOf(housePicInfo.get("averagePrice")))){
                    tvjunPrice.setText(StringUtil.valueOf(housePicInfo.get("averagePrice"))+"元/㎡");
                }
            }
            count.setText( currentPosition + 1 + "/" + list.size());

            adapter.OnItemClick(new PictureViewPager.OnItemClickListen() {
                @Override
                public void OnItemClick(int  position) {
                    isShow = !isShow;
                    if (isShow){
                        toplayout.startAnimation(mShowAnim);
                        bottomlayout.startAnimation(mShowAnim);
                        toplayout.animate().alpha(1f).setListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                toplayout.setVisibility(View.VISIBLE);
                            }
                        });
                        bottomlayout.animate().alpha(1f).setListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                bottomlayout.setVisibility(View.VISIBLE);
                            }
                        });
                    }else {
                        toplayout.startAnimation(hiddenAmin);
                        bottomlayout.startAnimation(hiddenAmin);
                        toplayout.animate().alpha(0f).setListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                toplayout.setVisibility(View.INVISIBLE);
                            }
                        });
                        bottomlayout.animate().alpha(0f).setListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                bottomlayout.setVisibility(View.INVISIBLE);
                            }
                        });
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private class getImageCacheAsyncTask extends AsyncTask<String, Void, File> {
        private final Context context;

        public getImageCacheAsyncTask(Context context) {
            this.context = context;
        }

        @Override
        protected File doInBackground(String... params) {
            String imgUrl = params[0];
            try {
                return Glide.with(context)
                        .load(imgUrl)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                        .get();
            } catch (Exception ex) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(File result) {
            if (result == null) {
                return;
            }
            //此path就是对应文件的缓存路径
            String path = result.getPath();
            Bitmap bmp = BitmapFactory.decodeFile(path);
            if (bmp != null) {
                CustomToast.showToast(HouseTypeActivity.this, "保存成功", 2000);
            } else {
                CustomToast.showToast(HouseTypeActivity.this, "保存失败", 2000);
            }
            SavePicture(bmp);
        }

        private void SavePicture(Bitmap bitmap) {
            File appDir = new File(Environment.getExternalStorageDirectory(), "HouseTypePicture");//在SD卡中创建一个文件夹
            if (!appDir.exists()) {//如果该文件夹不存在，则创建一个文件夹
                appDir.mkdir();
            }
            try {
                String fileName = System.currentTimeMillis() + ".jpg";
                File file = new File(appDir, fileName);
                FileOutputStream out = null;
                out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.flush();
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(file);
                intent.setData(uri);
                HouseTypeActivity.this.sendBroadcast(intent);//这个广播的目的就是更新图库，发了这个广播进入相册就可以找到你保存的图片了！，记得要传你更新的file哦

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
